package cn.simple.manager.web;

import cn.simple.manager.todo.ResponseEntity;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;
import org.thymeleaf.util.ArrayUtils;

import java.io.*;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.io.File.separator;

@Controller
@RequestMapping("/api/upload")
public class UpLoadFileController {

    private final static Object FILELOCK =new Object();
    private static InputStream apply(MultipartFile f) {
        try {
            return f.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    };

    @Value("${imageFilePath}")
    private String tempImageFilePath;


    /**
     * 图片批量上传
     * @param file
     * @param tag  栏目名称 标签
     * @return
     */
    @RequestMapping("/imageBatch")
    @ResponseBody
    public ResponseEntity uploadImageBatch(@RequestParam("file") MultipartFile[] file, @RequestParam(value = "tag", required = false) String tag){
        if(!ObjectUtils.isEmpty(file)){
            List<MultipartFile> multipartFiles = filterUpload(file,new String[]{"jpg","jpge","png","bpm","gif"});
            List<Map<String,String>> resault = new ArrayList<>(multipartFiles.size());
            try {
                String createDirectory = createImageFile(tempImageFilePath,tag);
                for(MultipartFile multipar : multipartFiles){
                    Map<String,String> fileEneity = new HashMap<>();
                    byte[] bytes = multipar.getBytes();
                    String md5str = DigestUtils.md5DigestAsHex(bytes);
                    String name = md5str+ "." + FilenameUtils.getExtension(multipar.getOriginalFilename());
                    String path = createDirectory+File.separator + name;
                    File checkFile = new File(tempImageFilePath+ File.separator+ path);
                    if(!checkFile.exists()){
                        IOUtils.copy(new ByteArrayInputStream(bytes),new FileOutputStream(tempImageFilePath+ File.separator+ path));
                    }
                    fileEneity.put("md5",md5str);
                    fileEneity.put("filename",FilenameUtils.getBaseName(multipar.getOriginalFilename()));
                    fileEneity.put("url",FilenameUtils.separatorsToUnix(path));
                    fileEneity.put("suffix","."+FilenameUtils.getExtension(multipar.getOriginalFilename()));
                    resault.add(fileEneity);
                }
                return ResponseEntity.ok(resault);
            } catch (IOException e) {
                e.printStackTrace();
                ResponseEntity.ERRO(e.getMessage());
            }
//            DigestUtils.md5Digest()
        }
//            IOUtils.copy(f.getInputStream(),new FileOutputStream(""));

//        FileUtils.cop
        return null;
    }

    public String createImageFile(String file_path,String tag) throws IOException {
        String dirpath = createFile(file_path);
        if(StringUtils.isEmpty(tag)){
            return dirpath;
        }
        String path = file_path+File.separator+dirpath+ File.separator+ tag;
        FileUtils.forceMkdir(new File(path));
        return dirpath+ File.separator+ tag;
    }

    public String  createFile (String file_path) throws IOException {
        String  createDirectory = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
        File checkFile = new File(file_path+File.separator+ createDirectory+ File.separator);
        if(!checkFile.exists()){
            synchronized (FILELOCK){
                FileUtils.forceMkdir(checkFile);
            }
        }
        return createDirectory;
    }

    public List<MultipartFile> filterUpload(MultipartFile[] multipartFiles, String... accat){
        return uploadFileBatch(multipartFiles, mult->{
            System.out.println(Arrays.toString(accat)+"--------"+FilenameUtils.getExtension(mult.getOriginalFilename()).toLowerCase());
            return ArrayUtils.contains(accat, FilenameUtils.getExtension(mult.getOriginalFilename()).toLowerCase());
        });
    }

    public List<MultipartFile> uploadFileBatch(MultipartFile[] multipartFiles , Predicate<MultipartFile> filter){
              return  Stream.of(multipartFiles).filter(filter)
                        .collect(Collectors.toList());
    }
}
